package com.toKnow.controller;

import com.toKnow.model.vo.CommonResult;
import com.toKnow.service.WelcomeService;
import com.toKnow.utils.JwtUserCookieUtil;
import com.toKnow.utils.SessionAndCookieUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 处理网站首页相关：包括欢迎页免登录，用户登录登出
 */
@Controller
@RequestMapping("/api")
public class WelcomeController {

    @Resource
    private WelcomeService welcomeService;

    /**
     * 欢迎页面，暂时为显示登录与注册表单，之后可能是网站的文章等页面
     * /welcome
     */
    @RequestMapping(value = "/")
    public String welcome(){
        return "index"; // 转发到welcome.jsp
    }

    /**
     * 网站首页，通过cookie检查是否可以免登录
     * /
     * GET{}{commonResult:CommonResult}
     */
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult index(HttpServletRequest request, HttpServletResponse response){
        CommonResult cm = new CommonResult(); //默认失败
        cm.setSuccess(false);
        cm.setMessage("以游客身份进入网站");
        //获取cookie
        Cookie[] cookies = request.getCookies();
        String username = null;
        String userpwd = null;
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if("userToken".equals(cookie.getName())){
                    String userCookieToken = cookie.getValue();
                    if(JwtUserCookieUtil.verify(userCookieToken)){
                        username = JwtUserCookieUtil.getInfo(userCookieToken, "username");
                        userpwd = JwtUserCookieUtil.getInfo(userCookieToken, "userpwd");
                    }
                }
            }
        }
        //检查是否可以免登录
        if(username != null && userpwd != null){
            //查询是否有该用户
            Integer id = welcomeService.confirmLogin(username, userpwd);
            //判断是否登录成功
            if(id > 0){ //登录成功
                //设置session
                SessionAndCookieUtil.setUserSession(request, String.valueOf(id), username, userpwd);
                //自动延长cookie10天
                SessionAndCookieUtil.setUserCookie(request, response, username, userpwd, 60 * 60 * 24 * 10);
                // 进入用户主页
                cm.setSuccess(true);
                cm.setMessage("免登录成功");
            }
        }
        return cm;
    }

    /**
     * ajax请求用户登录。ajax应控制登录成功则跳转到主页，登录失败则保持不变
     * /login
     * POST{account:String,userpwd:String}{commonResult:CommonResult}
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(HttpServletRequest request, HttpServletResponse response,
                              String account, String userpwd){
        CommonResult cm = new CommonResult();
        //将account统一转为username登录
        String username = welcomeService.getUsernameFromAccount(account);
        Integer id = welcomeService.confirmLogin(username, userpwd);
        //检查是否登录成功
        if(id > 0){
            //设置session
            SessionAndCookieUtil.setUserSession(request, String.valueOf(id), username, userpwd);
            //设置cookie 10天
            SessionAndCookieUtil.setUserCookie(request, response, username, userpwd, 60 * 60 * 24 * 10);
            //设置状态
            cm.setSuccess(true);
            cm.setMessage("登录成功，正在跳转至主页……");
        }else{
            //销毁cookie
            SessionAndCookieUtil.setUserCookie(request, response, "", "", 0);
            //设置状态
            cm.setSuccess(false);
            cm.setMessage("登录失败，请激活用户或检查输入的账号密码！");
        }
        return cm;
    }

    /**
     * 用户登出，清除session和cookie，跳转到网站首页
     * /logout
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
//    public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session){
//        //关闭session
//        if(session != null){
//            session.invalidate();
//        }
//        //销毁cookie
//        SessionAndCookieUtil.setUserCookie(request, response, "", "", 0);
//        return "redirect:/welcome"; //进入欢迎页面
//    }
    public CommonResult logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        CommonResult cm = new CommonResult();
        //关闭session
        if (session != null) {
            session.invalidate();
        }
        //销毁cookie
        SessionAndCookieUtil.setUserCookie(request, response, "", "", 0);
        cm.setSuccess(true);
        cm.setMessage("logout success");
        return cm; //进入欢迎页面
    }

}